﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WSIMWindowsClient.WSIMMessaging;
using System.IO;

namespace WSIMWindowsClient
{
    public partial class ChatForm : Form
    {
        private long fellow;
        private long sender;
        private string nick;
        private bool dataPresent;

        public long Fellow
        {
            get { return fellow; }
            set { fellow = value; }
        }

        public ChatForm(long userTo,string nick,MainForm parent)
        {
            
            InitializeComponent();

            this.fellow = userTo;
            this.nick = nick;
            this.sender = parent.ClientStatus.UserId;
            this.MdiParent = parent;
            this.Show();

            this.DragDrop += new DragEventHandler(txtMessages_DragDrop);
            
            this.DragOver += new DragEventHandler(txtMessages_DragEnter);
            this.FormClosing += new FormClosingEventHandler(ChatForm_FormClosing);
            this.txtMessages.LinkClicked += new LinkClickedEventHandler(txtMessages_LinkClicked);
            this.contextMenuStrip1.Opening += new CancelEventHandler(contextMenuStrip1_Opening);
        }

        void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            RichTextBox t = sender as RichTextBox;
            if (string.IsNullOrEmpty(txtMessages.SelectedText))
            {
                copiaToolStripMenuItem.Enabled = false;
            }
            else
            {
                copiaToolStripMenuItem.Enabled = true;
            }
            incollaToolStripMenuItem.Visible = false;   
        }

        void txtMessages_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }

        void ChatForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        void txtMessages_DragEnter(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent("FileNameW"))
            {
                e.Effect = DragDropEffects.None;
            }
            else
            {
                e.Effect = DragDropEffects.Copy;
                string[] str = (string[])e.Data.GetData("FileNameW");
                dataPresent = true;
            }
        }

        void txtMessages_DragDrop(object sender, DragEventArgs r)
        {

            if (dataPresent)
            {
                if (MessageBox.Show(this, "Do you want to transfer file?", "Attention!", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    DragEventArgs e = (DragEventArgs)r;
                    Array str = e.Data.GetData(DataFormats.FileDrop) as Array;
                    int i = 0;

                    foreach (string currStr in str)
                    {
                        FileStream outf = new FileStream(currStr, FileMode.Open);
                        if (outf.Length > 10485760)
                        {
                            MessageBox.Show(this, "File too big!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        }
                        else
                        {
                            byte[] b = new byte[outf.Length];
                            outf.Read(b, 0, (int)outf.Length);

                            WSIMMessaging.Message m = new WSIMWindowsClient.WSIMMessaging.Message();
                            m.Sender = this.sender;
                            m.Receiver = fellow;                            
                            m.IsText = false;
                            m.Attachment=new Attachment();
                            m.Attachment.Content=b;
                            m.Attachment.Filename=new FileInfo(currStr).Name;
                            m.Attachment.Lenght=(int)outf.Length;
                            m.MsgDate = DateTime.Now;
                            txtMessages.AppendText("Start transferring file...");
                            txtMessages.ScrollToCaret();
                            ObjectFactory.GetMessagingWS(false).BeginSendMessage(new SendMessageRequest(m), new AsyncCallback(endSendFile), null);
                            PostSendControlOperations();
                            outf.Close();
                        }
                    }
                    
                    
                }
                dataPresent = false;
            }
        }


        public void NewMessage(WSIMMessaging.Message msg) {
            if (msg.IsText)
            {
                txtMessages.Font = new Font(txtMessages.Font, FontStyle.Bold);
                txtMessages.AppendText(String.Format("{0} says at [{1}]: \n\t{2}\n", nick, msg.MsgDate, msg.Text));
                txtMessages.ScrollToCaret();
                txtMessages.Font = new Font(txtMessages.Font, FontStyle.Regular);
            }
            else {
                
                string fnlocal = (this.MdiParent as MainForm).ReceivedPath + @"\" + msg.Attachment.Filename;
                if (File.Exists(fnlocal)) File.Delete(fnlocal);
                FileStream str = new FileStream(fnlocal, FileMode.Create);
                
                str.Write(msg.Attachment.Content , 0, msg.Attachment.Lenght);
                str.Close();
                txtMessages.AppendText("File received!");
                txtMessages.ScrollToCaret();
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            WSIMMessaging.Message m = new WSIMWindowsClient.WSIMMessaging.Message();
            m.Sender = this.sender;
            m.Receiver = fellow;
            m.Text = txtSendMessage.Text;
            m.IsText = true;
            m.MsgDate = DateTime.Now;
            ObjectFactory.GetMessagingWS(false).BeginSendMessage(new SendMessageRequest(m), new AsyncCallback(endSendMessage), null);
            PostSendControlOperations();
            txtMessages.AppendText(String.Format("You say at [{0}]: \n\t{1}\n", m.MsgDate, m.Text));
            txtMessages.ScrollToCaret();
        }

        private void endSendFile(IAsyncResult ar)
        {
            ObjectFactory.GetMessagingWS(false).EndSendMessage(ar);
            txtMessages.AppendText("File transfer completed!\n");
            txtMessages.ScrollToCaret();
        }

        private void endSendMessage(IAsyncResult ar) {
            ObjectFactory.GetMessagingWS(false).EndSendMessage(ar);

        }

        private void ChatForm_Load(object sender, EventArgs e)
        {
            PostSendControlOperations();
        }

        private void PostSendControlOperations() {
            txtSendMessage.Text = "";
            txtSendMessage.Focus();            
        }

        private void copiaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(txtMessages.SelectedText);
        }

        private void cmdSendFile_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            FileStream outf = new FileStream(openFileDialog1.FileName, FileMode.Open);
            if (outf.Length > 10485760)
            {
                MessageBox.Show(this, "File too big!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            else
            {
                byte[] b = new byte[outf.Length];
                outf.Read(b, 0, (int)outf.Length);

                WSIMMessaging.Message m = new WSIMWindowsClient.WSIMMessaging.Message();
                m.Sender = this.sender;
                m.Receiver = fellow;
                m.IsText = false;
                m.Attachment = new Attachment();
                m.Attachment.Content = b;
                m.Attachment.Filename = new FileInfo(openFileDialog1.FileName).Name;
                m.Attachment.Lenght = (int)outf.Length;
                m.MsgDate = DateTime.Now;
                txtMessages.AppendText("Start transferring file...\n");
                txtMessages.ScrollToCaret();
                ObjectFactory.GetMessagingWS(false).BeginSendMessage(new SendMessageRequest(m), new AsyncCallback(endSendFile), null);
                PostSendControlOperations();
                outf.Close();
            }
                    
        }

    }
}
